using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Daemon.Common.WxHelper
{
    public class WxApiService : IWxApiService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        public WxApiService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<PublicAuthResult> PublicAuth(string appId, string secret)
        {
            var httpClient = _httpClientFactory.CreateClient();
            var authResponse = await httpClient.GetAsync($"?grant_type=client_credential&appid=${appId}&secret=${secret}");
            var content = await authResponse.Content.ReadAsStringAsync();
            var authResult = JsonConvert.DeserializeObject<PublicAuthResult>(content);
            return authResult;
        }

        public async Task<PublicAuthResult> PublicCodeAuth(string appId, string secret, string code)
        {
            var httpClient = _httpClientFactory.CreateClient();
            var authResponse = await httpClient.GetAsync($"https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code&appid=${appId}&secret=${secret}&code=${code}");
            var content = await authResponse.Content.ReadAsStringAsync();
            var authResult = JsonConvert.DeserializeObject<PublicAuthResult>(content);
            return authResult;
        }

        public async Task<WxUserInfo> PublicUserInfo(string accessToken, string openId)
        {
            var httpClient = _httpClientFactory.CreateClient();
            var authResponse = await httpClient.GetAsync($"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}&lang=zh_CN");
            var content = await authResponse.Content.ReadAsStringAsync();
            var authResult = JsonConvert.DeserializeObject<WxUserInfo>(content);
            return authResult;
        }
    }
}